import React, { useContext } from 'react'
import './index.less'
import http from '../../utils/http'
import { ContextAPI } from '../../App'
import { Observer } from 'mobx-react'

import {
  Form,
  Input,
  Button,
  message,
} from 'antd';
import {
  UserOutlined,
  LockOutlined
} from '@ant-design/icons';


const Login = () => {

  const context = useContext(ContextAPI)

  //获得form
  const [form] = Form.useForm();
  //登陆按钮
  const onFinish = async (event) => {
    const res = await http.post('/login/land', event)
    if (res.error !== 0) return message.error('登陆失败')
    message.success('登陆成功')
    window.sessionStorage.setItem('userInfo', JSON.stringify(res.data))
    window.sessionStorage.setItem('token', res.data.token)
    context.login.landChange()
  }
  //重置表单
  const onReset = () => {
    form.resetFields();
  }

  return (
    <div className='loginBox'>
      <Observer>
        {() => (
          <div className='loginMin'>
            <Form
              form={form}
              name="normal_login"
              className="login-form"
              initialValues={{
                remember: true,
              }}
              onFinish={onFinish}
            >
              <Form.Item
                name="phone"
                rules={[
                  { required: true, message: '手机号必须输入' },
                  {
                    pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                    message: '请确认手机号是否输入正确',
                  },
                ]}
              >
                <Input
                  prefix={<UserOutlined className="site-form-item-icon" />}
                  placeholder="手机" />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[
                  { required: true, message: '密码必须输入' },
                  { min: 4, message: '密码至少4位' },
                  { max: 12, message: '密码最多12位' },
                  { pattern: /^[a-zA-Z0-9_]+$/, message: '密码必须是英文、数字或下划线组成' }
                ]}
              >
                <Input
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  type="password"
                  placeholder="密码"
                />
              </Form.Item>

              <Form.Item>
                <Button type="primary" htmlType="submit" className="login-form-button" block>
                  登陆
                </Button>
                <Button htmlType="button" onClick={onReset} block>
                  重置
                </Button>
              </Form.Item>
            </Form>
          </div>
        )}
      </Observer>
    </div>
  )
}


export default Login
